package com.ziyun.erp.web.api.quoteFastPrintMaterial;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.utility.StringUtils;
import com.ziyun.erp.common.e.quote.SinglepairTypeEnum;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.quoteAttribute.entity.QuoteAttributeOptionEntity;
import com.ziyun.erp.modules.quoteAttribute.service.QuoteAttributeOptionService;
import com.ziyun.erp.modules.quoteFactoryMaterial.entity.QuoteFactoryMaterialEntity;
import com.ziyun.erp.modules.quoteFactoryMaterial.service.QuoteFactoryMaterialService;
import com.ziyun.erp.modules.quoteFastPrint.service.QuoteFastPrintService;
import com.ziyun.erp.modules.quoteFastPrintGroupPrice.entity.QuoteFastPrintGroupPriceEntity;
import com.ziyun.erp.modules.quoteFastPrintGroupPrice.service.QuoteFastPrintGroupPriceService;
import com.ziyun.erp.modules.quoteFastPrintMaterial.entity.QuoteFastPrintMaterialEntity;
import com.ziyun.erp.modules.quoteFastPrintMaterial.service.QuoteFastPrintMaterialService;
import com.ziyun.erp.modules.quotePrintFactoryPrice.entity.QuotePrintFactoryPriceEntity;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;


/**
 * 快印材料
 *
 * @author llc
 * @email 
 * @date 2018-09-19 09:04:01
 */
@RestController
@RequestMapping("port/quoteFastPrintMaterial/quotefastprintmaterial/")
public class QuoteFastPrintMaterialApi {
    @Autowired
    private QuoteFastPrintMaterialService quoteFastPrintMaterialService;

    @Autowired
    private QuoteAttributeOptionService quoteAttributeOptionService;

    @Autowired
    private QuoteFastPrintService quoteFastPrintService;

    @Autowired
    private QuoteFastPrintGroupPriceService quoteFastPrintGroupPriceService;

    @Autowired
    private QuoteFactoryMaterialService quoteFactoryMaterialService;
    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestBody Map<String, Object> paramBodyMap){
        //商户id
        Integer sellerId = Integer.valueOf(paramBodyMap.get("sellerId").toString());
        List<QuoteFastPrintMaterialEntity> list= quoteFastPrintMaterialService.selectFacotoryMaterialList(sellerId);
        PageUtils page=new PageUtils(list,100,50,1);
        return R.ok().put("page", page);
    }

    /**
     * 查看详情
     */

    @RequestMapping("/detail")
    public R detail(@RequestBody Map<String, Object> paramBodyMap){
        //商户id
        Integer sellerId = Integer.valueOf(paramBodyMap.get("sellerId").toString());
        //optionId
        Integer optionId=Integer.valueOf(paramBodyMap.get("optionId").toString());
        //根据optionId查询optionName,已勾选的
        QuoteAttributeOptionEntity quoteAttributeOptionEntity= quoteAttributeOptionService.selectById(optionId);
        String optionName=quoteAttributeOptionEntity.getOptionName();
        //封装查询参数
        Map<String,Object> params=new HashMap<>();
        params.put("factoryId",sellerId);
        params.put("optionName",optionName);
        List<Map<String,Object>> detailOptionName2List= quoteFastPrintMaterialService.selectDetailList(params);
        return R.ok().put("detailOptionName2List", detailOptionName2List);
    }

    /**
     * 查看所有材料
     */
    @RequestMapping("/findAllMaterial")
    public R findAllMaterial(){
        List<String>  quoteOptionNameList= quoteFastPrintMaterialService.findAllMaterial();
        return R.ok().put("quoteOptionNameList", quoteOptionNameList);
    }

    /**
     * 查看所有optionName2(克重)
     */
    @RequestMapping("/findAllOptionName2")
    public R findAllOptionName2(@RequestBody Map<String, Object> paramBodyMap){
        String optionName=paramBodyMap.get("optionName").toString();
        List<Map<String,Object>> quoteOptionName2List= quoteFastPrintMaterialService.findAllOptionName2(optionName);
        return R.ok().put("quoteOptionName2List", quoteOptionName2List);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody Map<String, Object> paramBodyMap){
        List<QuoteFactoryMaterialEntity>     quoteFactoryMaterialList=JsonUtils.string2Collection(paramBodyMap.get("quoteFactoryMaterialList").toString(),List.class,QuoteFactoryMaterialEntity.class);
        List<QuoteFactoryMaterialEntity>     addQuoteFactoryMaterialList=new ArrayList<QuoteFactoryMaterialEntity>();
        for (int i=0;i<quoteFactoryMaterialList.size();i++){
            QuoteFactoryMaterialEntity quoteFastPrintMaterial=quoteFactoryMaterialList.get(i);
            int count = quoteFactoryMaterialService.selectCount(new EntityWrapper<QuoteFactoryMaterialEntity>()
                    .eq("factory_id", quoteFastPrintMaterial.getFactoryId()).eq("option_id", quoteFastPrintMaterial.getOptionId()).eq("del_flag", 0)
                    .eq("material_type","shumakuaiyin"));
            if(count==0){
                addQuoteFactoryMaterialList.add(quoteFastPrintMaterial);
            }
        }
        if(addQuoteFactoryMaterialList.size()>0){
            quoteFactoryMaterialService.insertBatch(addQuoteFactoryMaterialList);
        }else{
            return R.error("添加的材料已经存在!请勿重复添加!");
        }
        return  R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public R update(@RequestBody Map<String, Object> paramBodyMap){
        String ids=paramBodyMap.get("ids").toString();
        //商户id
        Integer sellerId = Integer.valueOf(paramBodyMap.get("sellerId").toString());
        //修改人
        String updateUser=paramBodyMap.get("updateUser").toString();
//        QuoteAttributeOptionEntity quoteAttributeOptionEntity2 = null;
        if(StringUtils.isNotBlank(ids)){
            //把ids转换回数组
            String[] idArray=ids.split(",");
            //根据optionId查询optionName,已勾选的
            QuoteAttributeOptionEntity quoteAttributeOptionEntity= quoteAttributeOptionService.selectById(idArray[0]);
            String optionName=quoteAttributeOptionEntity.getOptionName();
            //封装查询参数
            Map<String,Object> params=new HashMap<>();
            params.put("factoryId",sellerId);
            params.put("optionName",optionName);
            List<Integer> selectedList=quoteFastPrintMaterialService.selectSelectedlList(params);
            List<Integer> addList=new ArrayList<Integer>();
            //查询出之前配置的材料
            for (int i=0;i<idArray.length;i++){
               if(!selectedList.contains(Integer.parseInt(idArray[i]))){
                   addList.add(Integer.parseInt(idArray[i]));
               }
            }
            //再重新插入数据
            for (int i=0;i<addList.size();i++){
                QuoteFastPrintMaterialEntity quoteFastPrintMaterial=new QuoteFastPrintMaterialEntity();
                quoteFastPrintMaterial.setFactoryId(sellerId);
                quoteFastPrintMaterial.setOptionId(addList.get(i));
                quoteFastPrintMaterial.setMaterialPrice(new BigDecimal(0));
                quoteFastPrintMaterial.setCreateDate(new Date());
                quoteFastPrintMaterial.setCreateUser(updateUser);
                quoteFastPrintMaterial.setUpdateDate(new Date());
                quoteFastPrintMaterial.setUpdateUser(updateUser);
                quoteFastPrintMaterial.setMaterialType("shumakuaiyin");
                quoteFastPrintMaterialService.insert(quoteFastPrintMaterial);
            }
            if(addList.size()==0){
                return R.error("添加的材料已经存在！");
            }
        }
        return R.ok();
    }


    /**
     * 查看所有快印打印机
     */
    @RequestMapping("/printList")
    public R printList(@RequestBody Map<String, Object> paramBodyMap){
        //商户id
        Integer sellerId = Integer.valueOf(paramBodyMap.get("sellerId").toString());
       List<QuotePrintFactoryPriceEntity>  printList=quoteFastPrintService.findAllFastPrint(sellerId);
       //默认选中单面
       for (int i=0;i<printList.size();i++){
           printList.get(i).setSingleDoubleFace("danmian");
       }
       return R.ok().put("printList", printList).put("singlepairTypeEnum",JsonUtils.enumToList(SinglepairTypeEnum.class));
    }


    /**
     * 生成组合
     */
    @RequestMapping("/generateGroup")
    public R generateGroup(@RequestBody Map<String, Object> paramBodyMap){
        List<Object> quoteFastPrintGroupPrice=JsonUtils.string2Collection(paramBodyMap.get("quoteFactoryMaterialList").toString(),List.class,Object.class);
        //商户id
        Integer sellerId = Integer.valueOf(paramBodyMap.get("sellerId").toString());
        //修改人
        String updateUser=paramBodyMap.get("updateUser").toString();
        //创建集合封装数据，批量插入
        List<QuoteFastPrintGroupPriceEntity> batchQuoteFastPrintGroupList=new ArrayList<QuoteFastPrintGroupPriceEntity>();
        //从quote_fast_print_group_price表查询出已经生成过的组合防止重复生成,参数为factory_id
        List<String> groupExistList=quoteFastPrintGroupPriceService.findExistList(sellerId);
       //传过来的数据，先取集合中的第一个元素为打印机相关参数
        List<Map<String,Object>> quotePrintFactoryPriceList= (List<Map<String,Object>>) quoteFastPrintGroupPrice.get(0);
       //取第二个集合为材料相关参数
        List<Map<String,Object>> optionList= (List<Map<String, Object>>) quoteFastPrintGroupPrice.get(1);
        //遍历第一个集合
        for (int i=0;i<quotePrintFactoryPriceList.size();i++){
            Map<String,Object>  fastPrintGroup= quotePrintFactoryPriceList.get(i);
            //遍历第二个集合
            for(int k=0;k<optionList.size();k++){
                //如果是单面或者双面
                if(!fastPrintGroup.get("singleDoubleFace").toString().equals("danshuangmian"))
                {
                    QuoteFastPrintGroupPriceEntity quoteFastPrintGroup=new QuoteFastPrintGroupPriceEntity();
                    quoteFastPrintGroup.setFactoryId(sellerId);
                    quoteFastPrintGroup.setPrintConfigId(Integer.parseInt(fastPrintGroup.get("id").toString()));
                    //根据optionId从quote_factory_material查询MaterialId
                    QuoteFactoryMaterialEntity quoteFactoryMaterialEntity= quoteFactoryMaterialService.selectOne(new EntityWrapper<QuoteFactoryMaterialEntity>().eq("option_id",optionList.get(k).get("option_id")).eq("factory_id",sellerId));
                    //设置材料id
                    quoteFastPrintGroup.setMaterialId(quoteFactoryMaterialEntity.getOptionId());
                    //单双面设置
                    quoteFastPrintGroup.setSingleDoubleFace(fastPrintGroup.get("singleDoubleFace").toString().equals("danmian")?"single_face":"double_face");
                    //设置创建时间
                    quoteFastPrintGroup.setCreateDate(new Date());
                    //设置创建人
                    quoteFastPrintGroup.setCreateUser(updateUser);
                    //拼接参数
                    StringBuffer buffer=new StringBuffer();
                    String str=buffer.append(quoteFastPrintGroup.getFactoryId()).
                            append(quoteFastPrintGroup.getPrintConfigId()).
                            append(quoteFastPrintGroup.getMaterialId()).
                            append(quoteFastPrintGroup.getSingleDoubleFace()).toString();
                    //判断是否已经生成过,没生成过的添加到集合中
                    if(!groupExistList.contains(str)) {
                        //添加数据到集合中
                        batchQuoteFastPrintGroupList.add(quoteFastPrintGroup);
                    }
                }else{
                    //如果单双面都有则需一次生成单面，双面
                    QuoteFastPrintGroupPriceEntity quoteFastPrintGroupSingle=new QuoteFastPrintGroupPriceEntity();
                    quoteFastPrintGroupSingle.setFactoryId(sellerId);
                    quoteFastPrintGroupSingle.setPrintConfigId(Integer.parseInt(fastPrintGroup.get("id").toString()));
                    //根据optionId从quote_factory_material查询MaterialId
                    QuoteFactoryMaterialEntity quoteFactoryMaterialEntity= quoteFactoryMaterialService.selectOne(new EntityWrapper<QuoteFactoryMaterialEntity>().eq("option_id",optionList.get(k).get("option_id")).eq("factory_id",sellerId));
                    //设置材料id
                    quoteFastPrintGroupSingle.setMaterialId(quoteFactoryMaterialEntity.getId());
                    //单双面设置
                    quoteFastPrintGroupSingle.setSingleDoubleFace("single_face");
                    //设置创建时间
                    quoteFastPrintGroupSingle.setCreateDate(new Date());
                    //设置创建人
                    quoteFastPrintGroupSingle.setCreateUser(UserUtils.getCurentUser().getUsername());
                    //再创建一个对象
                    QuoteFastPrintGroupPriceEntity quoteFastPrintGroupDouble=new QuoteFastPrintGroupPriceEntity();
                    quoteFastPrintGroupDouble.setFactoryId(1);
                    quoteFastPrintGroupDouble.setPrintConfigId(Integer.parseInt(fastPrintGroup.get("id").toString()));
                    //设置材料id
                    quoteFastPrintGroupDouble.setMaterialId(quoteFactoryMaterialEntity.getOptionId());
                    //单双面设置
                    quoteFastPrintGroupDouble.setSingleDoubleFace("double_face");
                    //设置创建时间
                    quoteFastPrintGroupDouble.setCreateDate(new Date());
                    //设置创建人
                    quoteFastPrintGroupDouble.setCreateUser(updateUser);
                    //拼接参数
                    StringBuffer buffer1=new StringBuffer();
                    String str1=buffer1.append(quoteFastPrintGroupSingle.getFactoryId()).
                            append(quoteFastPrintGroupSingle.getPrintConfigId()).
                            append(quoteFastPrintGroupSingle.getMaterialId()).
                            append(quoteFastPrintGroupSingle.getSingleDoubleFace()).toString();
                    //判断是否已经生成过,没生成过的添加到集合中
                    if(!groupExistList.contains(str1)) {
                        //添加数据到集合中
                        batchQuoteFastPrintGroupList.add(quoteFastPrintGroupSingle);
                    }
                    //拼接参数
                    StringBuffer buffer2=new StringBuffer();
                    String str2=buffer2.append(quoteFastPrintGroupDouble.getFactoryId()).
                            append(quoteFastPrintGroupDouble.getPrintConfigId()).
                            append(quoteFastPrintGroupDouble.getMaterialId()).
                            append(quoteFastPrintGroupDouble.getSingleDoubleFace()).toString();
                    if(!groupExistList.contains(str2)){
                        //添加数据到集合中
                        batchQuoteFastPrintGroupList.add(quoteFastPrintGroupDouble);
                    }
                }
            }
        }
        if(batchQuoteFastPrintGroupList.size()>0){
            quoteFastPrintGroupPriceService.insertBatch(batchQuoteFastPrintGroupList,batchQuoteFastPrintGroupList.size());
        }
        return  R.ok();
    }

     /**
     * 获取对应的信息和已勾选的信息
     */
    @RequestMapping("/info")
    public R info(@RequestBody Map<String, Object> paramBodyMap){
        //商户id
        Integer sellerId = Integer.valueOf(paramBodyMap.get("sellerId").toString());
        //查询id
        Integer id = Integer.valueOf(paramBodyMap.get("id").toString());
        //先根据id去quote_factory_material查询option_id；
        QuoteFactoryMaterialEntity quoteFactoryMaterial=quoteFactoryMaterialService.selectById(id);
        //根据optionId查询optionName,已勾选的
        QuoteAttributeOptionEntity quoteAttributeOptionEntity= quoteAttributeOptionService.selectById(quoteFactoryMaterial.getOptionId());
        String optionName=quoteAttributeOptionEntity.getOptionName();
        //封装查询参数
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("factoryId",sellerId);
        params.put("optionName",optionName);
        //已经勾选过了
        List<Map<String,Object>> selectOptionName2List= quoteFastPrintMaterialService.selectDetailList(params);
        //再从quote_attribute_option中查询所有的optionName2
        List<Map<String,Object>> quoteOptionName2List= quoteFastPrintMaterialService.findAllOptionName2(optionName);
        //查询出已勾选的索引
        List<Integer> indexList=new ArrayList<Integer>();
        for (int i=0;i<quoteOptionName2List.size();i++){
            Map<String,Object> map= quoteOptionName2List.get(i);
            for(int k=0;k<selectOptionName2List.size();k++){
                if(selectOptionName2List.get(k).get("option_name2").equals(map.get("optionName2"))){
                    indexList.add(i);
                    break;
                }
            }
        }
        return R.ok().put("quoteOptionName2List", quoteOptionName2List).put("indexList",indexList);
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Map<String, Object> paramBodyMap){
        //商户id
        Integer sellerId = Integer.valueOf(paramBodyMap.get("sellerId").toString());
        //修改人
        String updateUser=paramBodyMap.get("updateUser").toString();
        //查询id
        Integer[] optionIds =JsonUtils.string2Array(paramBodyMap.get("optionIds").toString(),Integer.class);
        List<QuoteFastPrintMaterialEntity> updaList=new ArrayList<QuoteFastPrintMaterialEntity>();
        for (int i=0;i<optionIds.length;i++){
            //根据optionId查询optionName,已勾选的
            QuoteAttributeOptionEntity quoteAttributeOptionEntity= quoteAttributeOptionService.selectById(optionIds[i]);
            String optionName=quoteAttributeOptionEntity.getOptionName();
            //封装查询参数
            Map<String,Object> params=new HashMap<>();
            params.put("factoryId",sellerId);
            params.put("optionName",optionName);
            //从quote_factory_material找到所有待删除的option_id
            List<QuoteFastPrintMaterialEntity> delList= quoteFastPrintMaterialService.getMateriallList(params);
            for(int k=0;k<delList.size();k++){
                QuoteFastPrintMaterialEntity quoteFastPrintMaterialEntity=delList.get(k);
                quoteFastPrintMaterialEntity.setUpdateUser(updateUser);
                quoteFastPrintMaterialEntity.setUpdateDate(new Date());
                quoteFastPrintMaterialEntity.setDelFlag(true);
                updaList.add(quoteFastPrintMaterialEntity);
            }
        }
        if(updaList.size()>0){
            quoteFastPrintMaterialService.updateBatchById(updaList);
        }else{
            return R.error("没有可删除材料");
        }
        return R.ok();
    }

    /**
     * 修改是否启用
     */
    @RequestMapping("/updateDisplay")
    public R updateDisplay(@RequestBody Map<String, Object> paramBodyMap) {
        //修改的id
        Integer id = Integer.valueOf(paramBodyMap.get("id").toString());
        //修改人
        String updateUser = paramBodyMap.get("updateUser").toString();
        QuoteFactoryMaterialEntity quoteFactoryMaterialEntity= quoteFactoryMaterialService.selectById(id);
        boolean flag=!quoteFactoryMaterialEntity.getDisplay();
        quoteFactoryMaterialEntity.setDisplay(flag);
        quoteFactoryMaterialEntity.setUpdateUser(updateUser);
        quoteFactoryMaterialEntity.setUpdateDate(new Date());
        quoteFactoryMaterialService.updateById(quoteFactoryMaterialEntity);
        return R.ok();
    }
}
